package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.INcCaiService;
import com.ruoyi.system.service.INcInputCfService;
import com.ruoyi.system.service.INcOrderCfService;
import com.ruoyi.system.service.INcOuputCfService;
import com.ruoyi.system.util.ExcelUtil2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 菜房出库 信息操作处理
 *
 * @author ruoyi
 * @date 2019-08-30
 */
@Controller
@RequestMapping("/system/ncOuputCf")
public class NcOuputCfController extends BaseController {
    private String prefix = "system/ncOuputCf";
    private String caifangPrefix="system/screen";

    @Autowired
    private INcOuputCfService ncOuputCfService;

    @Autowired
    private INcOrderCfService orderCfService;

    @Autowired
    private INcInputCfService ncInputCfService;
    @Autowired
    private INcCaiService ncCaiService;


    @RequiresPermissions("system:ncOuputCf:view")
    @GetMapping()
    public String ncOuputCf(Integer type, ModelMap mmap) {
        mmap.put("type", type);
        return prefix + "/ncOuputCf";
    }

    @GetMapping("/ncOuputCfAll")
    public String ncOuputCfAll(Integer type, ModelMap mmap) {
        mmap.put("type", type);
        return prefix + "/ncOuputCf-all";
    }

    @GetMapping("/ncOuputCfToday")
    public String ncOuputCfToday(Integer type, ModelMap mmap, String date) {
        mmap.put("type", type);
        if (StringUtils.isNotEmpty(date)) {
            mmap.put("today", date);
        } else {
            mmap.put("today", DateUtils.parseDateToStr("yyyy-MM-dd",new Date()));
        }
        return prefix + "/ncOuputCf-today";
    }

    /**
     * 查询菜房出库列表
     */
    @RequiresPermissions("system:ncOuputCf:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcOuputCf ncOuputCf, int type) {
        startPage();
        if (type > 0) {
            ncOuputCf.getParams().put("cforderFor", type);
        }
        List<NcOuputCf> list = ncOuputCfService.selectNcOuputCfList(ncOuputCf);
        return getDataTable(list);
    }

    /**
     * 查询菜房出库列表
     */
    @PostMapping("/listTodays")
    @ResponseBody
    public TableDataInfo listTodays(NcOuputCf ncOuputCf, int type, String today) {
        startPage();
        if (type > 0) {
            ncOuputCf.getParams().put("cforderFor", type);
        }

        if (StringUtils.isEmpty(today)) {
            ncOuputCf.getParams().put("outputTime", new Date());
        } else {
            try {
                ncOuputCf.getParams().put("outputTime", DateUtils.parseDate(today, "yyyy-MM-dd"));
            } catch (Exception e) {
                e.printStackTrace();
                ncOuputCf.getParams().put("outputTime", new Date());
            }
        }
        List<NcOuputCf> list = ncOuputCfService.selectNcOuputCfList(ncOuputCf);
        return getDataTable(list);
    }


    /**
     * 导出菜房出库列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcOuputCf ncOuputCf, int type) {
        if (type > 0) {
            ncOuputCf.getParams().put("cforderFor", type);
        }
        List<NcOuputCf> list = ncOuputCfService.selectNcOuputCfList(ncOuputCf);
        ExcelUtil2<NcOuputCf> util = new ExcelUtil2<NcOuputCf>(NcOuputCf.class);

        if (1 == type) {
            return util.exportExcel(list, "菜房1出库订单");
        } else if (2 == type){
            return util.exportExcel(list, "菜房2出库订单");
        }else {
            return util.exportExcel(list, "菜房出库订单");
        }

    }

    /**
     * 新增菜房出库
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存菜房出库
     */
    @RequiresPermissions("system:ncOuputCf:add")
    @Log(title = "菜房出库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcOuputCf ncOuputCf) {
        return toAjax(ncOuputCfService.insertNcOuputCf(ncOuputCf));
    }

    /**
     * 修改菜房出库
     */
    @GetMapping("/edit/{outputId}")
    public String edit(@PathVariable("outputId") Integer outputId, ModelMap mmap) {
        NcOuputCf ncOuputCf = ncOuputCfService.selectNcOuputCfById(outputId);
        mmap.put("ncOuputCf", ncOuputCf);
        return prefix + "/edit";
    }

    /**
     * 修改保存菜房出库
     */
    @RequiresPermissions("system:ncOuputCf:edit")
    @Log(title = "菜房出库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcOuputCf ncOuputCf) {
        return toAjax(ncOuputCfService.updateNcOuputCf(ncOuputCf));
    }

    /**
     * 删除菜房出库
     */
    @RequiresPermissions("system:ncOuputCf:remove")
    @Log(title = "菜房出库", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncOuputCfService.deleteNcOuputCfByIds(ids));
    }


    /**
     * 确认出库
     */
    @GetMapping("/confirmOutput/{cforderId}")
    public String confirmOutput(@PathVariable("cforderId") Long cforderId, ModelMap mmap) {
        NcOrderCf orderCf = orderCfService.selectNcOrderCfById(cforderId);
        /*根据菜的品种找到库存中的菜*/
        NcOuputCf ncOuputCf = new NcOuputCf();
        ncOuputCf.setCforderId(cforderId);
        ncOuputCf.setCreateBy(ShiroUtils.getLoginName());
        ncOuputCf.setOutputUser(ShiroUtils.getLoginName());

        ncOuputCf.setCreateTime(new Date());
        ncOuputCf.setOutputTime(new Date());
        mmap.put("ncOuputCf", ncOuputCf);
        /*作物品种*/
        mmap.put("cropVarieties", orderCf.getCropVarieties());
        /*库存*/
        NcInputCf inputCf = new NcInputCf();
        inputCf.getParams().put("cropVarieties", orderCf.getCropVarieties());//品种
        List<NcInputCf> list = ncInputCfService.selectNcInputCfList(inputCf);

        if (list.size() > 0) {
            ncOuputCf.setRealAmout(list.get(0).getLeftAmount());
        }
        mmap.put("stocks", list);

        return prefix + "/edit-output";
    }


    /**
     * 确认出库
     */
    @GetMapping("/confirmOutputByStock/{inputId}")
    public String confirmOutputByStock(@PathVariable("inputId") Integer inputId, ModelMap mmap) {
        NcInputCf inputCf = ncInputCfService.selectNcInputCfById(inputId);

        /*根据菜的品种找到库存中的菜*/
        NcOuputCf ncOuputCf = new NcOuputCf();
        ncOuputCf.setCforderId(inputCf.getCforderId());
        ncOuputCf.setCreateBy(ShiroUtils.getLoginName());
        ncOuputCf.setOutputUser(ShiroUtils.getLoginName());

        ncOuputCf.setCreateTime(new Date());
        ncOuputCf.setOutputTime(new Date());
        ncOuputCf.setInputId(inputId);
        ncOuputCf.setRealAmout(inputCf.getLeftAmount());
        mmap.put("ncOuputCf", ncOuputCf);
        /*库存*/
        List<NcInputCf> list = new ArrayList<>();
        list.add(inputCf);

        mmap.put("stocks", list);

        return prefix + "/edit-output";
    }


    /**
     * 蔬菜出库
     */
    @Log(title = "蔬菜出库", businessType = BusinessType.INSERT)
    @PostMapping("/saveOutput")
    @ResponseBody
    public AjaxResult saveOutput(NcOuputCf ncOuputCf) {
        /*库存更新数量*/
        NcInputCf inputCf = ncInputCfService.selectNcInputCfById(ncOuputCf.getInputId());

        if (ncOuputCf.getRealAmout().compareTo(inputCf.getLeftAmount()) > 0) {

            return AjaxResult.error("出库数量大于库存！");
        }


        /*更改订单状态 为已入库*/
        NcOrderCf orderCf = orderCfService.selectNcOrderCfById(ncOuputCf.getCforderId());
        orderCf.setCforderStatus("5");//已完成
        orderCf.setFinishTime(new Date());
        orderCfService.updateNcOrderCf(orderCf);


        ncOuputCf.setCreateTime(new Date());
        ncOuputCf.setOutputUser(ShiroUtils.getLoginName());
        ncOuputCf.setStatus("1");

        inputCf.setLeftAmount(inputCf.getLeftAmount().subtract(ncOuputCf.getRealAmout()));
        ncInputCfService.updateNcInputCf(inputCf);

        return toAjax(ncOuputCfService.insertNcOuputCf(ncOuputCf));
    }

    /**
     * 确认生成出库单
     */
    @Log(title = "确认生成出库单", businessType = BusinessType.OTHER)
    @PostMapping("/confirmTable")
    @ResponseBody
    public AjaxResult confirmTable(String ids, Integer caifangType) {
        SysUser user = ShiroUtils.getSysUser();
        return toAjax(ncOuputCfService.createOutputOrderByIds(ids, user, caifangType));
    }
    //大屏蔬菜整理间1 2
    @GetMapping("/caifang/{id}")
    public String selectCFoutPutScreen(ModelMap map,@PathVariable(name="id") Integer id){
        //id =1 菜房1，id= 2，菜房2
        Calendar cal = Calendar.getInstance();
        //获取最近7天的数据
        List<Double> cforder = new ArrayList<Double>();
        NcOuputCf  cf= new NcOuputCf();
        cf.getParams().put("cf",id);
        cf.setStatus("2");
        String[] last7Day = last7Day(cal);
        for (int i = 0; i < last7Day.length; i++) {
            cf.getParams().put("day", last7Day[i]);
            double amount = ncOuputCfService.selectCFoutPutScreen(cf);
            cforder.add(amount);
        }
        map.put("cforder", cforder);
        map.put("date", last7Day);
        //各类别菜的占比
        NcOrderCf orderCf=new NcOrderCf();

        orderCf.setCforderFor(id);

        NcCai cai = new NcCai();
        cai.setAncestors("0");
        cai.setParentId(new Long(0));
        List<NcCai> result = ncCaiService.selectBigClass(cai);
        //各品种菜的统计次数
        List<Integer> longs=new ArrayList<>();
        //各品种菜名称
        List<String> caiName=new ArrayList<String>();
        //统计占比
        List<String> ratio=new ArrayList<>();
        for(int i=0;i<result.size();i++){
            caiName.add(result.get(i).getCaiName());
            orderCf.getParams().put("ancestors", result.get(i).getCaiId());
            Integer count=orderCfService.caiScreen(orderCf);
            longs.add(count);
        }
        double sumCount=0;
        for(Integer s:longs){
            sumCount += s;
        }
        for(int i=0;i<longs.size();i++){
            if(sumCount == 0){
                ratio.add("0.00");
            }
            else{
                Integer l=longs.get(i);
                ratio.add(new DecimalFormat("0.00").format(Double.valueOf(l / sumCount * 100)));
            }
        }
        List<NcCai> ncCaiList=new ArrayList<NcCai>();
        for(int i=0;i<result.size();i++){
            NcCai nc=new NcCai();
            nc.setCaiName(caiName.get(i));
            nc.setCaiId(result.get(i).getCaiId());
            Map hashMap=new HashMap();
            hashMap.put("longs",longs.get(i));
            hashMap.put("ratio",ratio.get(i));
            nc.setPlanCounts(hashMap);
            ncCaiList.add(nc);
        }
        map.put("ncCai",ncCaiList);

        //今日入库蔬菜
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String day = format2.format(Calendar.getInstance().getTime());
        Calendar cal1=Calendar.getInstance();
        cal1.add(Calendar.DATE, -1);
        String yesterday = format2.format(cal1.getTime());

        NcInputCf  inputCf= new NcInputCf();
        inputCf.getParams().put("day",day);
        inputCf.setStatus("2");

        inputCf.getParams().put("cf",id);

        double todayInput=ncInputCfService.selectCFinPutScreen(inputCf);
        map.put("todayInput",todayInput);
        inputCf.getParams().put("day",yesterday);
        double lastDayInput=ncInputCfService.selectCFinPutScreen(inputCf);
        if(lastDayInput != 0){
            map.put("inputDayRatio", new DecimalFormat("0.00").format(Double.valueOf((todayInput - lastDayInput) / lastDayInput * 100)));
        }
        else{
            map.put("inputDayRatio", new DecimalFormat("0.00").format((double)Math.round(todayInput*100)));
        }
        //今日供应蔬菜
        NcOuputCf  cf1= new NcOuputCf();
        cf1.getParams().put("day",day);

        cf1.getParams().put("cf",id);

        cf1.setStatus("2");
        double today=ncOuputCfService.selectCFoutPutScreen(cf1);
        map.put("dayoutput",today);

        cf1.getParams().put("day",yesterday);
        double lastday=ncOuputCfService.selectCFoutPutScreen(cf1);
        if(lastday != 0){
            map.put("outputDayRatio", new DecimalFormat("0.00").format(Double.valueOf((today - lastday) / lastday * 100)));
        }
        else{
            map.put("outputDayRatio", new DecimalFormat("0.00").format((double)Math.round(today*100)));
        }
        //日均产出蔬菜
        NcOuputCf c=new NcOuputCf();
        Calendar ca=Calendar.getInstance();
        c.getParams().put("year",ca.get(Calendar.YEAR));
        c.setStatus("2");
        c.getParams().put("cf",id);
        List<NcOuputCf> cflist=ncOuputCfService.avgCFoutPutScreen(c);
         double sum=0;
         if(StringUtils.isNotEmpty(cflist)){
             for(NcOuputCf  output:cflist){
                 sum += output.getRealAmout().doubleValue();
             }
         }
        String avg;
         if(cflist.size() == 0){
              avg="0.00";
         }
         else{
              avg=new DecimalFormat("0.00").format(Double.valueOf(sum / cflist.size() ));
         }

        if(sum ==0){
            map.put("avgDay","0.00");
        }
        else{
            map.put("avgDay",avg);
        }
        NcOuputCf  out= new NcOuputCf();
        out.getParams().put("day",yesterday);
        List<NcOuputCf> cfyestDay=ncOuputCfService.avgCFoutPutScreen(out);
        if(cfyestDay.size() == 0){
            map.put("ratio","0.00");
        }
        else{
            map.put("ratio",new DecimalFormat("0.00").format((Double.valueOf(avg)-cfyestDay.get(0).getRealAmout().intValue()) / cfyestDay.get(0).getRealAmout().intValue() ));
        }

        return caifangPrefix+"/caifang";
    }
    //产生最近一周的时间
    public String[] last7Day(Calendar cal) {
        String[] last7Day = new String[7];
        for (int i = 0; i < 7; i++) {
            if (cal.get(Calendar.MONTH) + 1 < 10) {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }
            } else {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }

            }
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1); //逐次往前推1天*/

        }
        return last7Day;
    }


}
